package com.hyg.module_user.userInfo;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hyg.lib_base.MyView.SDCardImageSelect.CheckImageAdapter;
import com.hyg.lib_base.MyView.SDCardImageSelect.Folder;
import com.hyg.lib_base.MyView.SDCardImageSelect.FolderAdapter;
import com.hyg.lib_base.MyView.SDCardImageSelect.Image;
import com.hyg.lib_base.MyView.SDCardImageSelect.ImageModel;
import com.hyg.lib_base.Net.NetworkOP;
import com.hyg.lib_base.mainUtils.FileUtils;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_base.mainUtils.Utils;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.constant.UrlUtils;
import com.hyg.lib_common.constant.FileConstants;
import com.hyg.lib_common.sweetalertdialog.SweetAlertDialog;
import com.hyg.module_user.R;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import okhttp3.FormBody;

public class UpdateHeadIconActivity extends BaseActivity {

    private static final int REQUEST_CAPTURE = 100;
    //    private static final int REQUEST_PICK = 101;
    private static final int REQUEST_CROP_PHOTO = 102;
    public static  final int FINSH_RESULT = 104;//截图后的返回
    private static final int LOADER_ID = 0x0100;
//    private LoadCallBack mLoad = new LoadCallBack();

    private CheckImageAdapter checkImageAdapter;
    private ArrayList<Image> images = new ArrayList<>();
    //调用照相机返回图片文件
    private File tempFile;
    private static final int MIN_IMAGE_FILE_SIZE = 10 * 1024; // 最小的图片大小
    private ArrayList<Folder> mFolders;
    private Folder mFolder;
    private FolderAdapter folderAdapter;

    private ImageView back;
    private RecyclerView rv_update_head,rv_folder;
    private TextView check_folder;

    private Uri resultUri ;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_update_head_icon);

        init();
    }

    public void init(){
        StatusBarUtil.setStatusBar(1,this,getResources().getColor(R.color.white),00,null,null,true);
        back = (ImageView)findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {if(Utils.isFastClick()){return ;}
                finish();
                overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
            }
        });
        rv_update_head = findViewById(R.id.rv_update_head);
        rv_folder = findViewById(R.id.rv_folder);
        check_folder = (TextView)findViewById(R.id.check_folder);
        check_folder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(rv_folder.getVisibility() == View.VISIBLE){
                    rv_folder.setVisibility(View.GONE);
                }else {
                    rv_folder.setVisibility(View.VISIBLE);
                }
            }
        });
        setdata();
    }

    private MyHandler myHandler = new MyHandler(this);
    private static class MyHandler extends Handler {
        private final WeakReference<Context> reference;
        private UpdateHeadIconActivity activity;
        public MyHandler(Context context) {
            reference = new WeakReference<>(context);
            activity = (UpdateHeadIconActivity) reference.get();
        }
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1://个人信息保存
                    try {
                        JSONObject jsondata = new JSONObject(msg.obj.toString());//获取返回的JSONObject原对象
                        String status = URLDecoder.decode(jsondata.getString("code"), "utf-8");
                        String message = URLDecoder.decode(jsondata.getString("message"), "utf-8");
                        Log.d("welcomeadUUM", jsondata + "");

                        if (status.equals("200")) {
                            activity.editorn =activity.sn.edit();
                            activity.editorn.putString("headIconUrl",message);
                            activity.editorn.commit();
                            activity.saveHeadImg();
                        } else {
                            activity.ErrorDialog(message);
                        }
                    } catch (JSONException e) {
                        Log.d(CrashTAG,""+e.getMessage());
                    } catch (UnsupportedEncodingException e) {
                        Log.d(CrashTAG,""+e.getMessage());
                    }
                    break;
            }
        }
    }


    public void setdata(){
        rv_update_head.setNestedScrollingEnabled(false);
        rv_update_head.setLayoutManager(new GridLayoutManager(this,3));
        rv_update_head.setItemAnimator(new DefaultItemAnimator());
//        rv_update_head.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));//RV的item分割线
        checkImageAdapter = new CheckImageAdapter(UpdateHeadIconActivity.this,images);
        checkImageAdapter.setOnItemClickLitener(new CheckImageAdapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                if(position == 0){
                    //第一个就去照相
                    if(hasPermission(new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})){
                        gotoCamera();
                    }else {
                        requestPermission(0x02,new String[]{Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE});
                    }
                }else {
                    //这里点击获取到图片地址然后裁剪
//                    Log.d("jiejie", Uri.parse(images.get(position).path)+"");
                    if(!Utils.isEmpty(images.get(position).getPath())){
                        File tempFile = new File(images.get(position).getPath());
                        startUCrop(Uri.fromFile(tempFile));
                    }
                }
            }
            @Override
            public void onItemLongClick(View view, int position) {
            }
        });
        rv_update_head.setAdapter(checkImageAdapter);
    }
    /**
     * 初始化图片文件夹列表
     */
    private void initFolderList() {
        if (!Utils.isEmpty(mFolders )) {
            rv_folder.setLayoutManager(new LinearLayoutManager(this));
            folderAdapter = new FolderAdapter(this, mFolders);
            folderAdapter.setOnFolderSelectListener(new FolderAdapter.OnFolderSelectListener() {
                @Override
                public void OnFolderSelect(Folder folder) {
                    setFolder(folder);
                    rv_folder.setVisibility(View.GONE);
                }
            });
            rv_folder.setAdapter(folderAdapter);
        }
    }
    /**
     * 设置选中的文件夹，同时刷新图片列表
     *
     * @param folder
     */
    private void setFolder(Folder folder) {
        if (folder != null && folderAdapter != null && !folder.equals(mFolder)) {
            mFolder = folder;
            check_folder.setText(folder.getName());
            rv_update_head.scrollToPosition(0);
            updateSource(folder.getImages());
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        if(hasPermission(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE})){
//            getLoaderManager().initLoader(LOADER_ID,null,mLoad);
            loadImageForSDCard();
        }else {
            requestPermission(0x01,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE});
        }
    }

    /**
     * 从SDCard加载图片。
     */
    private void loadImageForSDCard() {
        ImageModel.loadImageForSDCard(this, new ImageModel.DataCallback() {
            @Override
            public void onSuccess(ArrayList<Folder> folders) {
                //folders是图片文件夹的列表，每个文件夹中都有若干张图片。
                mFolders = folders;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!Utils.isEmpty(mFolders)) {
                            initFolderList();
                            setFolder(mFolders.get(0));
                        }
                    }
                });
            }
        });
    }

//    private class LoadCallBack implements LoaderManager.LoaderCallbacks<Cursor>{
//        private final String[] IMAGE_PROJECTION = new String[]{
//                MediaStore.Images.Media._ID,//Id
//                MediaStore.Images.Media.DATA,//图片路径
//                MediaStore.Images.Media.DATE_ADDED//图片的创建时间
//        };
//
//        @Override
//        public Loader<Cursor> onCreateLoader(int id, Bundle args) {
//            //创建一个Loader
//            if(id == LOADER_ID){
//                //如果是我们的ID则进行初始化
//                return new CursorLoader(getBaseContext(),
//                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
//                        IMAGE_PROJECTION,
//                        null,
//                        null,
//                        IMAGE_PROJECTION[2] + " DESC");
//            }
//            return null;
//        }
//
//        @Override
//        public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
//            //当Loader加载完成时
//            List<Image> images = new ArrayList<>();
//            //判断是否有数据
//            if(data != null){
//                int count = data.getCount();
//                if(count > 0){
//                    data.moveToFirst();
//                    // 得到对应的列的Index坐标
//                    int indexId = data.getColumnIndexOrThrow(IMAGE_PROJECTION[0]);
//                    int indexPath = data.getColumnIndexOrThrow(IMAGE_PROJECTION[1]);
//                    int indexDate = data.getColumnIndexOrThrow(IMAGE_PROJECTION[2]);
//                    do {
//                        // 循环读取，直到没有下一条数据
//                        int id = data.getInt(indexId);
//                        String path = data.getString(indexPath);
//                        long dateTime = data.getLong(indexDate);
//
//                        File file = new File(path);
//                        if (!file.exists() || file.length() < MIN_IMAGE_FILE_SIZE) {
//                            // 如果没有图片，或者图片大小太小，则跳过
//                            continue;
//                        }
//                        // 添加一条新的数据
//                        Image image = new Image(path,dateTime,id+"");
//                        images.add(image);
//
//                    } while (data.moveToNext());
//                }
//            }
//            updateSource(images);
//        }
//
//        @Override
//        public void onLoaderReset(Loader<Cursor> loader) {
//            updateSource(null);
//        }
//    }

    /**
     * 通知Adapter数据更改的方法
     * @param images 新的数据
     */
    private void updateSource(List<Image> images){
        this.images.clear();
        this.images.add(new Image("",0,""));
        if(images == null || images.size() == 0) return;
        this.images.addAll(images);
        checkImageAdapter.notifyDataSetChanged();
    }

    /**
     *权限的返回
     */
//    @Override
//    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        switch(requestCode){
//            case 0x02:
//                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//                    gotoCamera();
//                }
//                break;
//            case 0x01:
//                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
////                    getLoaderManager().initLoader(LOADER_ID,null,mLoad);
//                    loadImageForSDCard();
//                }
//        }
//    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case REQUEST_CAPTURE://系统相机返回
                if(resultCode == RESULT_OK){
//                    Log.d("jiejie","--------相机---------" + Uri.fromFile(tempFile).toString());
//                    Log.d("jiejie","--------path----------" + getRealFilePathFromUri(UpdataHead.this,Uri.fromFile(tempFile)));
                    startUCrop(Uri.fromFile(tempFile));
                }

                break;
            case UCrop.REQUEST_CROP: {
                if (resultCode == RESULT_OK) {
                    // 裁剪照片
                    final Uri croppedUri = UCrop.getOutput(data);
                    if (croppedUri != null) {
                        if (FileUtils.isFileExists(croppedUri.getPath())) {
//                            save_msg.setVisibility(View.VISIBLE);
//                            showUriImg.setVisibility(View.VISIBLE);
                            resultUri = croppedUri;
//                            showUriImg.setImageURI(resultUri);
                            UpLoading();
                        }else{
//                            save_msg.setVisibility(View.INVISIBLE);
//                            showUriImg.setVisibility(View.INVISIBLE);
                            Toast.makeText(this, "未获取到头像路径,请重新选择裁剪", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        Toast.makeText(this, "头像本地保存失败。", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            }
            case UCrop.RESULT_ERROR: {
                if(resultCode == RESULT_OK) {
                    final Throwable cropError = UCrop.getError(data);
                    handleCropError(cropError);
                }
                break;
            }
        }
    }

    public void setUpdateHead() {
        Loading();
        File imgfile = new File(resultUri.getPath());
        String str_tag = "1";
        FormBody formBody = new FormBody.Builder()
                .add("token", sn.getString("token", ""))
                .build();
        NetworkOP op = new NetworkOP(str_tag, formBody, imgfile, myHandler, UrlUtils.addr_head);
        //使用类的对象op将三个实参发送，通过handler传递参数到NetworkOP中去，在NetworkOP将数据包装发送到规定的互联网地址
        op.okhttpAsyncFile();
    }

    public void UpLoading() {
        View view = View.inflate(this, R.layout.dialog_head_icon, null);
        final ImageView showUriImg = view.findViewById(R.id.showUriImg);
        showUriImg.setImageURI(resultUri);
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.NORMAL_TYPE);
        pDialog.setTitleText("确认使用该头像？");
        pDialog.setCustomView(view);
        pDialog.setConfirmButton("使用它!", new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                setUpdateHead();
//                saveHeadImg();
            }
        });
        pDialog.setCancelButton("换一张", new SweetAlertDialog.OnSweetClickListener() {
            public void onClick(SweetAlertDialog sweetAlertDialog) {
                sweetAlertDialog.dismiss();
            }
        });
//        pDialog.setCancelable(false);
        pDialog.show();
    }

    public void Loading() {
        View view = View.inflate(this, R.layout.dialog_loading, null);
        final TextView loadingText = view.findViewById(R.id.loadingText);
        loadingText.setText("正在为您上传头像中,请稍等一小会儿...");
        pDialog = new SweetAlertDialog(this, SweetAlertDialog.NORMAL_TYPE);
        pDialog.setCustomView(view);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    public void saveHeadImg(){
        if (!isFinishing() && pDialog.isShowing())
            pDialog.dismiss();
        editorn = sn.edit();
        editorn.putString(FileConstants.HeadIcon,resultUri.getPath());
        editorn.commit();
        Intent intent = new Intent();
        intent.setData(resultUri);
        setResult(RESULT_OK, intent);
        finish();
    }


    /**
     * 打开截图的界面     使用三方Ucrop工具
     * @param imageUri
     */
    private void startUCrop(Uri imageUri) { //裁剪后保存到文件中
        //checkDirPath(Environment.getExternalStorageDirectory().getPath()+ "/images/")
        Uri destinationUri = Uri.fromFile(new File(FileUtils.getDiskCacheDir(getApplicationContext()), "HeadImg"+System.currentTimeMillis()+".jpg"));

//        uCrop.withAspectRatio(1,1);//设置裁剪框的宽高比例
        UCrop.Options options = new UCrop.Options();
        options.setCompressionQuality(100);//设置裁剪图片的质量（0到100）
        options.setCompressionFormat(Bitmap.CompressFormat.JPEG);// (PNG 是无损的，会忽略质量设置)

        //下面参数分别是缩放,旋转,裁剪框的比例
        options.setAllowedGestures(UCropActivity.ALL, UCropActivity.ALL, UCropActivity.ALL);// 设置裁剪图片可操作的手势
        options.setFreeStyleCropEnabled(true);// 是否能调整裁剪框
        options.setToolbarTitle("可移动,旋转和缩放");//设置标题栏文字
        options.setCropGridStrokeWidth(1);//设置裁剪网格线的宽度(我这网格设置不显示，所以没效果)
        options.setCropFrameStrokeWidth(10);//设置裁剪框的宽度
        options.setHideBottomControls(false);//隐藏下边控制栏
        options.setShowCropGrid(true);  //设置是否显示裁剪网格
//        options.setCircleDimmedLayer(true);//设置是否为圆形裁剪框
        options.setShowCropFrame(false); //设置是否显示裁剪边框(true为方形边框)
        options.setMaxScaleMultiplier(8);//设置最大缩放比例
        options.setImageToCropBoundsAnimDuration(333);//设置图片在切换比例时的动画

        options.setToolbarWidgetColor(ActivityCompat.getColor(this, R.color.MainThemeColor));//标题字的颜色以及按钮颜色
        options.setDimmedLayerColor(Color.parseColor("#AA000000"));//设置裁剪外颜色
        options.setToolbarColor(Color.parseColor("#ffffff")); // 设置标题栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(this, R.color.MainThemeColor));//设置状态栏颜色
        options.setCropGridColor(Color.parseColor("#ffffff"));//设置裁剪网格的颜色
        options.setCropFrameColor(Color.parseColor("#ffffff"));//设置裁剪框的颜色

//        UCrop uCrop = UCrop.of(imageUri, destinationUri);
        UCrop.of(imageUri, destinationUri)
                .withOptions(options)
//        .withMaxResultSize(300, 300)
                .start(UpdateHeadIconActivity.this);
    }

    //处理剪切失败的返回值
    private void handleCropError(Throwable cropError) {
        deleteTempPhotoFile();
        if (cropError != null) {
            Toast.makeText(this, cropError.getMessage(), Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(this, "无法剪切选择图片", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 删除拍照临时文件
     */
    private void deleteTempPhotoFile() {
        File tempFile = new File(FileUtils.getDiskCacheDir(getApplicationContext()) + "output_temp.jpg");
        if (tempFile.exists() && tempFile.isFile()) {
            tempFile.delete();
        }
    }


    /**
     * 跳转到系统照相机
     */
    private void gotoCamera(){
        String SDState = Environment.getExternalStorageState();
        //判断SD卡是否存在
        if(SDState.equals(Environment.MEDIA_MOUNTED)){
            tempFile = new File(checkDirPath(FileUtils.getDiskCacheDir(getApplicationContext())), "output_temp.jpg");
            //隐式的打开调用系统相册
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
                intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                //如果是7.0及以上的系统使用FileProvider的方式创建一个Uri
//                Uri contentUri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".fileProvider", tempFile);
                Uri contentUri = FileProvider.getUriForFile(this, "sample.com.wisdomhealth" + ".fileProvider", tempFile);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
            }else {
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempFile));
            }
            intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            startActivityForResult(intent,REQUEST_CAPTURE);
        }
    }

    /**
     * 检查文件是否存在
     */
    private static String checkDirPath(String dirPath) {
        if (TextUtils.isEmpty(dirPath)) {
            return "";
        }
        File dir = new File(dirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        return dirPath;
    }
    /**
     * 判断是否有指定的权限
     */
    public boolean hasPermission(String... permissions) {

        for (String permisson : permissions) {
            if (ContextCompat.checkSelfPermission(this, permisson)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }
    /**
     * 申请指定的权限.
     */
    public void requestPermission(int code, String... permissions) {

        if (Build.VERSION.SDK_INT >= 23) {
            requestPermissions(permissions, code);
        }
    }

    @SuppressLint("NewApi")
    /**
     * 需要进行检测的权限数组
     */
    protected String[] needPermissions = {
            //            Manifest.permission.ACCESS_COARSE_LOCATION,
            //            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            //            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.REQUEST_INSTALL_PACKAGES,
            //            Manifest.permission.CALL_PHONE,
            Manifest.permission.CAMERA
    };
    private static final int PERMISSON_REQUESTCODE = 0;
    /**
     * 判断是否需要检测，防止不停的弹框
     */
    private boolean isNeedCheck = true;

    /**
     * 申请权限结果的回调方法
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] paramArrayOfInt) {
        super.onRequestPermissionsResult(requestCode, permissions, paramArrayOfInt);
        if (requestCode == PERMISSON_REQUESTCODE) {
        }
        switch(requestCode){
            case 0x02:
                if(paramArrayOfInt.length > 0 && paramArrayOfInt[0] == PackageManager.PERMISSION_GRANTED){
                    gotoCamera();
                }
//                if (!verifyPermissions(paramArrayOfInt)) {
//                    //                        isNeedCheck = false;
//                    //用户授权拒绝之后，友情提示一下就可以了
//                    Toast.makeText(this, "当前应用缺少权限，不能正常使用。请自行\"设置\"-\"权限\"-打开相机使用权限", Toast.LENGTH_SHORT).show();
//                }
                break;
            case 0x01:
                if(paramArrayOfInt.length > 0 && paramArrayOfInt[0] == PackageManager.PERMISSION_GRANTED){
                    //                    getLoaderManager().initLoader(LOADER_ID,null,mLoad);
                    loadImageForSDCard();
                }
//                if (!verifyPermissions(paramArrayOfInt)) {
////                        isNeedCheck = false;
//                    //用户授权拒绝之后，友情提示一下就可以了
//                    Toast.makeText(this, "当前应用缺少权限，不能正常使用。请自行\"设置\"-\"权限\"-打开文件读写存储权限", Toast.LENGTH_SHORT).show();
//                }
                break;
        }
    }

}